import { defineStore } from "pinia"
import { saveUserinfo } from "@/api/login"
import { getCountry, getClassify } from "@/api/common"

export const useStore = defineStore('main',{
	state: () => ({
		userinfo: {
			user_bg: '',
			add_time: null,
			addres: "",
			avatar: "",
			birthday: "",
			card_id: "",
			group_id: 0,
			is_basic: 0,
			is_del: 0,
			last_time: null,
			level: 0,
			login_type: "",
			mark: "",
			nickname: "",
			phone: "",
			real_name: "",
			sex: 0,
			status: 1,
			uid: 1,
			uniqid: "",
			address: "",
			total_collect: 0,
			total_fans: 0,
			total_posts: 0,
			hidden_sub: 1,
			hidden_fans: 1,
			hidden_collect: 1,
			hidden_star: 1,
			hidden_pub: 1,
		},
		news: {
			star_num: 0,
			comment_num: 0,
			fans_num: 0,
			sys_msg_num: 0,
			total: 0
		},
		fans: {},
		stars: {},
		countrys: [],
		classifys: []
	}),
	getters: {
		getUserinfo: function(){
			return this.userinfo
		},
		getCountryList: function(){
			return this.countrys
		},
		getClassifyList: function(){
			return this.classifys
		},
		getNews: function(){
			return this.news
		}
	},
	actions: {
		getCountryLabel: function(value:string | number){
			const list = this.countrys.filter((item:any) => item.value === value)
			return list.length > 0 ? list[0].label : undefined
		},
		getStar: function(value: number){
			return this.stars[value] || 0
		},
		setStar: function(value: number, flag: number){
			return this.stars[value] = flag
		},
		getFans: function(value: number){
			return this.fans[value] || 0
		},
		setFans: function(value: number, flag: number){
			return this.fans[value] = flag
		},
		setUserinfo: function(userinfo:any){
			this.userinfo = Object.assign(this.userinfo, userinfo)
		},
		saveIp: function(){
			uni.request({
			    url:'http://ip-api.com/json/',
				method:'POST',
				success: (res:any):void => {
					saveUserinfo({
						address: res.data.city,
						last_ip: res.data.query
					})
					this.setUserinfo({
						address: res.data.city,
						last_ip: res.data.query
					})
				}
			})
		},
		saveCountryList: function(){
			getCountry().then((res:any) => {
				const locale = uni.getLocale().replace("-",'_')
				this.countrys = res.data.map((item:any) => {
					return {
						label: item[locale],
						value: item.iso
					}
				})
			})
		},
		saveClassifyList: function(){
			getClassify().then((res:any) => {
				const locale = uni.getLocale().replace("-",'_')
				this.classifys = res.data.map((item:any) => {
					return {
						label: item[locale],
						value: item.id
					}
				})
			})
		},
		saveNews: function(news:any){
			this.news = news
		}
	}
})